<?php

namespace app\http\middleware;

use app\qsapi\model\BanLog;
use app\qsapi\model\BoxMemberInfo;
use app\qsapi\model\Member;
use app\qsapi\service\MemberService;
use think\cache\driver\Redis;

class QsApiCheckLogin
{
    public function handle($request, \Closure $next)
    {
        $module=request()->module();
        $controller=request()->controller();
        $action=request()->action();
        if(!$controller || !$action){
            return json(api_message([], "请登录", 402));
        }

        $class = new \ReflectionClass('app\\'.$module.'\controller\\'.$controller);
        $properties=$class->getDefaultProperties();
        $noNeedLogin = $properties['noNeedLogin'] ?? [];
        $needLogin = $properties['needLogin'] ?? [];
        // 登录校验
        if (!in_array($action,$noNeedLogin, false)  &&   !in_array($action,$needLogin, false)  ) {
            // 获取Token
            $token = request()->header("Authorization");
            if ($token && strpos($token, 'Bearer ') !== false) {
                $token = str_replace("Bearer ", null, $token);
                //校验redis
                $redis = new Redis([
                    'host' => Env('redis.host'),
                    'port' => Env('redis.port'),
                    'password' => Env('redis.password'),
                    'prefix = yun_phone_'
                ]);
                $bool = $redis->has($token);
                if (!$bool) {
                    return json(api_message([], "请登录", 401));
                }
                // JWT解密token
                $jwt = new \Jwt();
                $userId = $jwt->verifyToken($token);
                if (!$userId) {
                    // token解析失败跳转登录页面
                    return json(api_message([], "请登录", 401));
                }
                $logOff = (new Member())->field('log_off')->where('id',$userId)->find();
                if($logOff['log_off'] == 2){
                    return json(api_message([], "您的账号已完成注销，如用已注销账号重新登录千年游戏盒子则视为新账号，请您知晓~", 4003));
                }

                $member = (new MemberService())->getInfo($userId);
                if (!$member) {
                    return json(api_message([], "请登录", 401));
                }
                //查找封禁
                $banLog=new BanLog();
                $banLogInfo=$banLog->where('member_id',$userId)->where('type',1)->find();
                $banLogInfo=$banLogInfo?$banLogInfo->toArray():[];
                if ($banLogInfo && ($banLogInfo['ban_time'] != 0 && time() < $banLogInfo['ban_time'] )) {
                    $day = diffTimeRetrunDay($banLogInfo['create_time'], $banLogInfo['ban_time']);
                    return json(api_message(['ban_rule' => $banLogInfo['ban_rule'], 'ban_time' => $banLogInfo['ban_time'], 'day' => $day], "封禁中", 402));
                }


                request()->hook('getMemberId', function () use ($userId) {
                    return $userId;
                });
            } else {
                return json(api_message([], "请登录", 401));
            }
        }else if (in_array($action,$needLogin, false)){
            $token = request()->header("Authorization");
            if ($token && strpos($token, 'Bearer ') !== false) {
                $token = str_replace("Bearer ", null, $token);
                //校验redis
                $redis = new Redis([
                    'host' => Env('redis.host'),
                    'port' => Env('redis.port'),
                    'password' => Env('redis.password'),
                    'prefix = yun_phone_'
                ]);
                $bool = $redis->has($token);
                if (!$bool) {
                    return json(api_message([], "请登录", 401));
                }
                // JWT解密token
                $jwt = new \Jwt();
                $userId = $jwt->verifyToken($token);
                if (!$userId) {
                    // token解析失败跳转登录页面
                    return json(api_message([], "请登录", 401));
                }
                $logOff = (new Member())->field('log_off')->where('id',$userId)->find();
                if($logOff['log_off'] == 2){
                    return json(api_message([], "您的账号已完成注销，如用已注销账号重新登录千年游戏盒子则视为新账号，请您知晓~", 4003));
                }
                $member = (new MemberService())->getInfo($userId);
                if (!$member) {
                    return json(api_message([], "请登录", 401));
                }
                //查找封禁
                $banLog=new BanLog();
                $banLogInfo=$banLog->where('member_id',$userId)->where('type',1)->find();
                $banLogInfo=$banLogInfo?$banLogInfo->toArray():[];
                if ($banLogInfo && ($banLogInfo['ban_time'] != 0 && time() < $banLogInfo['ban_time'] )) {
                    $day = diffTimeRetrunDay($banLogInfo['create_time'], $banLogInfo['ban_time']);
                    return json(api_message(['ban_rule' => $banLogInfo['ban_rule'], 'ban_time' => $banLogInfo['ban_time'], 'day' => abs($day)], "封禁中", 402));
                }
                request()->hook('getMemberId', function () use ($userId) {
                    return $userId;
                });
            }else{
                //未登录时候  用户id 为 0
                request()->hook('getMemberId', function ()  {
                    return 0;
                });
            }
        }
        return $next($request);
    }
}
